package svc

import (
	"context"
	"fmt"
	"os"
	"searchcenter/internal/config"
	"searchcenter/internal/es"
	"searchcenter/internal/middleware"
	"time"

	"github.com/zeromicro/go-zero/rest"
)

type ServiceContext struct {
	Config   config.Config
	ESClient *es.ESClient
	Auth     rest.Middleware
}

func NewServiceContext(c config.Config) *ServiceContext {
	esClient, err := es.NewESClient(
		c.ES.Addresses,
		c.ES.ApiKey,
		es.WithTimeout(time.Duration(c.ES.Timeout)*time.Second),
	)
	if err != nil {
		panic("ES client init failed: " + err.Error())
	}

	// 初始化所有配置的索引
	for _, indexCfg := range c.ESIndexConfigs {
		if indexCfg.AutoCreate {
			var mapping string
			if indexCfg.MappingFile != "" {
				// 从文件加载映射
				data, err := os.ReadFile(indexCfg.MappingFile)
				if err != nil {
					panic(fmt.Sprintf("load mapping file failed for %s: %v",
						indexCfg.Name, err))
				}
				mapping = string(data)
			} else {
				// 使用默认映射
				mapping = getDefaultMapping(indexCfg.Name)
			}

			if err := esClient.CreateIndexIfNotExists(
				context.Background(),
				indexCfg.Name,
				mapping,
			); err != nil {
				panic(fmt.Sprintf("create index %s failed: %v",
					indexCfg.Name, err))
			}
		}
	}

	return &ServiceContext{
		Config:   c,
		ESClient: esClient,
		Auth:           middleware.NewAuthMiddleware(c.JWT.AccessSecret),
	}
}

// 获取默认映射配置
func getDefaultMapping(indexName string) string {
	switch indexName {
	case "blog":
		return `{
            "mappings": {
                "properties": {
                    "id": {"type": "long"},
                    "AuthorId": {"type": "long"},
                    "title": {
                        "type": "text",
                        "analyzer": "ik_max_word",
                        "search_analyzer": "ik_smart"
                    },
                    "content": {
                        "type": "text",
                        "analyzer": "ik_max_word",
                        "search_analyzer": "ik_smart"
                    },
                    "likeNum": {"type": "integer"},
                    "readNum": {"type": "integer"},
                    "createTime": {
                        "type": "date",
                        "format": "yyyy-MM-dd HH:mm:ss||epoch_millis"
                    },
                    "tags": {"type": "keyword"},
                    "category": {"type": "keyword"}
                }
            }
        }`
	case "user":
		return `{
            "mappings": {
                "properties": {
                    "id": {"type": "long"},
                    "username": {
                        "type": "text",
                        "fields": {
                            "keyword": {"type": "keyword"}
                        }
                    },
                    "email": {"type": "keyword"},
                    "createdAt": {
                        "type": "date",
                        "format": "yyyy-MM-dd HH:mm:ss"
                    }
                }
            }
        }`
	default:
		return "{}" // 空映射
	}
}
